package com.atguigu.gulimall.order.web;

import com.atguigu.gulimall.order.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;
    @GetMapping("/{page}.html")
    public String page(@PathVariable("page") String page){
        return page;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo=orderService.confirmOrder();
        model.addAttribute("orderConfirm",orderConfirmVo);
        return "confirm";
    }
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes redirectAttributes){
        try {
            SubmitOrderResponseVo submitOrderResponseVo=orderService.submitOrder(orderSubmitVo);
            if (submitOrderResponseVo.getCode()==0){
                model.addAttribute("order",submitOrderResponseVo.getOrder());
                return "pay";
            }else {
                String msg = "下单失败;";
                switch (submitOrderResponseVo.getCode()){
                    case 1:msg+="订单超时";
                    case 2:msg+="价格发生变化";
                    case 3:msg+="库存不足";
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";

            }
        }catch (NoStockException e){
            String msg = "下单失败，商品无库存";
            redirectAttributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }catch (Exception e){
            String msg = "订单异常";
            redirectAttributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }



//        下单成功来到支付页
//        下单失败回到订单确认页重新下单
    }
}
